package com.skillworld.webapp.web.pages.rest.user;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.tapestry5.annotations.ContentType;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SessionState;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.Request;

import com.skillworld.webapp.model.user.User;
import com.skillworld.webapp.model.userservice.InvalidFacebookTokenException;
import com.skillworld.webapp.model.userservice.UserService;

import com.skillworld.webapp.web.util.ErrorMessages;
import com.skillworld.webapp.web.util.UserSession;

import es.udc.pojo.modelutil.exceptions.InstanceNotFoundException;

@ContentType("text/xml")
public class FacebookLogin {
    
    @SuppressWarnings("unused")
    @Property
    private String errorMessage = null;
    
    @Property
    private User user;
    
    @SuppressWarnings("unused")
    @Property
    private String jsessionId;
    
    @Inject
    private UserService userService;

    @SuppressWarnings("unused")
    @SessionState(create=false)
    private UserSession userSession;
    
    private boolean userSessionExists;
    
    @Inject
    private Request request;
    
    @Inject
    private HttpServletRequest httpServletRequest;
   

    void onPassivate() 
    {
        return;
    }
    
    void onActivate()
    {
        if (userSessionExists)
        {
            errorMessage = ErrorMessages.ALREADY_LOGGED_IN;
            return;
        }
        
        String facebookId = request.getParameter("fb");
        String authorizationToken = request.getParameter("token");
    
        if(facebookId == null || authorizationToken == null)
        { 
            errorMessage = ErrorMessages.INVALID_ARGUMENTS;
            return;
        }

        try 
        {
            user = this.userService.facebookUserLogin(facebookId, authorizationToken);
            // Creates the user session, so the user keeps logged-in 
            HttpSession httpSession = httpServletRequest.getSession(true);
            jsessionId = httpSession.getId();
            /*
             * 2 hours to invalidate a session
             * Just a quick&dirty fix !
             */
            httpSession.setMaxInactiveInterval(2 * 3600);
            userSession = new UserSession(user.getUserId(), facebookId, authorizationToken);
        }
        catch (InvalidFacebookTokenException e)
        { 
            errorMessage = ErrorMessages.INVALID_AUTHORIZATION_TOKEN; 
        }
        catch (InstanceNotFoundException e)
        {
            errorMessage = ErrorMessages.NOT_REGISTERED;
        }
    }   
    
}
